package com.ukefu.util.task.export;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.UCKeFuTime;
import com.ukefu.util.UKTools;
import com.ukefu.util.extra.DataExchangeInterface;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.web.model.MetadataTable;
import com.ukefu.webim.web.model.SysDic;
import com.ukefu.webim.web.model.TableProperties;
import com.ukefu.webim.web.model.UKeFuDic;
import com.ukefu.webim.web.model.User;

@SuppressWarnings("deprecation")
public class ExcelExporterProcess {
	private XSSFWorkbook  wb; 
	private Sheet sheet; 
	private CellStyle firstStyle = null ;
	
	private int rowNum ;
	
	private List<Map<String ,Object>> values ;
	private MetadataTable table ;
	private OutputStream output ;
	private Row titleRow ;
	
	public ExcelExporterProcess(List<Map<String ,Object>> values , MetadataTable table , OutputStream output) {
		this.values = values ;
		this.table = table ;
		this.output = output;
		wb = new XSSFWorkbook();
		sheet = wb.createSheet();
		firstStyle = createFirstCellStyle();
		createHead() ;
	}
	public void process() throws IOException{
		createContent();
		if(table!=null){
			int inx = 0 ;
			for(TableProperties tp : table.getTableproperty()){
				if(tp.isUnresize() == false) {
					sheet.autoSizeColumn(inx++) ;
				}
			}
			for(TableProperties tp : table.getTableproperty()){
				if(tp.isUnresize() == true) {
					List<SysDic> dicList = UKeFuDic.getInstance().getDic("com.dic.xiaoe.input") ;
					for(@SuppressWarnings("unused") SysDic sysDic : dicList) {
						sheet.autoSizeColumn(inx++) ;	
					}
				}
			}
			wb.write(this.output);
		}
	}
	
	/**
	 * 构建头部
	 */
	private void createHead(){
		titleRow = sheet.createRow(rowNum);
		if(table!=null && table.getTableproperty()!=null){
			int inx = 0 ;
			for(TableProperties tp : table.getTableproperty()){
				if(tp.isUnresize() == false) {
					Cell cell2 = titleRow.createCell(inx++); 
					cell2.setCellStyle(firstStyle); 
					cell2.setCellValue(new XSSFRichTextString(tp.getName()));
				}
			}
			for(TableProperties tp : table.getTableproperty()){
				if(tp.isUnresize() == true) {
					List<SysDic> dicList = UKeFuDic.getInstance().getDic("com.dic.xiaoe.input") ;
					for(SysDic sysDic : dicList) {
						Cell cell2 = titleRow.createCell(inx++); 
						cell2.setCellStyle(firstStyle); 
						cell2.setCellValue(new XSSFRichTextString(sysDic.getName()));
					}
				}
			}
		}
		rowNum ++ ;
	}
	
	private CellStyle createContentStyle(){
		CellStyle cellStyle = wb.createCellStyle(); 
		
		cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐 
		cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐 
		cellStyle.setWrapText(false);// 指定单元格自动换行 

		// 设置单元格字体 
		Font font = wb.createFont(); 
		//font.setFontName("微软雅黑"); 
		font.setFontHeight((short) 200); 
		cellStyle.setFont(font); 
		cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
		return cellStyle ;
	}
	
	/**
	 * 首列样式
	 * @return
	 */
	private CellStyle createFirstCellStyle(){
		CellStyle cellStyle = baseCellStyle();
		Font font = wb.createFont();
		//font.setFontName("微软雅黑"); 
		font.setFontHeight((short) 180);
		cellStyle.setFont(font);
		
		cellStyle.setWrapText(false);
		
		cellStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
		cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
		
	
		return cellStyle;
	}
	
	
	private synchronized void createContent(){
		CellStyle cellStyle = createContentStyle() ;
		if(table!=null && table.getTableproperty()!=null){
			for(Map<String , Object> value:values){
				Row row2 = sheet.createRow(rowNum);
				List<ExportData> tempExportDatas = new ArrayList<ExportData>();
				int cols = 0 ;
				for(TableProperties tp : table.getTableproperty()){
					if(tp.isUnresize() == false) {
						Cell cell2 = row2.createCell(cols++); 
						cell2.setCellStyle(cellStyle); 
						if(value.get(tp.getFieldname().toLowerCase())!=null){
							if(tp.isModits()) {
								@SuppressWarnings("unchecked")
								List<String> list = (List<String>)value.get(tp.getFieldname().toLowerCase());
								if(list.size()>0) {
									cell2.setCellValue(new XSSFRichTextString(list.remove(0)));
								}
								ExportData expData = new ExportData(tp , list) ;
								if(list.size()>0) {
									tempExportDatas.add(expData) ;
									if(list.size() > expData.getMaxcols()) {
										expData.setMaxcols(list.size());
									}
								}
							}else if(tp.isSeldata()){
								SysDic sysDic = UKeFuDic.getInstance().getDicItem(String.valueOf(value.get(tp.getFieldname().toLowerCase()))) ;
								if(sysDic!=null) {
									cell2.setCellValue(new XSSFRichTextString(sysDic.getName()));
								}else {
									List<SysDic> dicItemList = UKeFuDic.getInstance().getSysDic(tp.getSeldatacode());
									if(dicItemList!=null && dicItemList.size() > 0) {
										for(SysDic dicItem : dicItemList) {
											String s = "";
											Object obj = value.get(tp.getFieldname().toLowerCase());
											if(obj instanceof Boolean) {
												s = (Boolean)obj?"1":"0";
											}else {
												s= String.valueOf(value.get(tp.getFieldname().toLowerCase()));
											}
											if(dicItem.getCode().equals(s)) {
												cell2.setCellValue(new XSSFRichTextString(dicItem.getName())); break ;
											}
										}
									}
								}
							}else if(tp.isReffk() && !StringUtils.isBlank(tp.getReftbid())){
								String key = (String) value.get(tp.getFieldname().toLowerCase()) ;
								String orgi = (String) value.get("orgi") ;
								if(!StringUtils.isBlank(key) && !StringUtils.isBlank(orgi)) {
				            		DataExchangeInterface exchange = (DataExchangeInterface) UKDataContext.getContext().getBean(tp.getReftbid()) ;
				            		Object refvalue = exchange.getDataByIdAndOrgi(key, orgi) ;
				            		if(refvalue!=null) {
				            			cell2.setCellValue(new XSSFRichTextString(refvalue.toString()));
				            		}
								}
							}else{
								boolean writed = false ;
								if(!StringUtils.isBlank(String.valueOf(value.get("distype")))){
									if(value.get("disphonenum")!=null && value.get("disphonenum").equals(value.get(tp.getFieldname()))){
										cell2.setCellValue(new XSSFRichTextString(UKTools.processSecField(String.valueOf(value.get(tp.getFieldname().toLowerCase())),String.valueOf(value.get("distype")))));
										writed = true ;
									}
								}
								if(writed == false){
									if(!StringUtils.isBlank(tp.getPlugin())) {
										if(tp.getPlugin().equals("sectime") && String.valueOf(value.get(tp.getFieldname().toLowerCase())).matches("[\\d]{1,}")) {
											int sectime = (int)Long.parseLong(String.valueOf(value.get(tp.getFieldname().toLowerCase()))) ;
											cell2.setCellValue(new XSSFRichTextString(new UCKeFuTime(0,0,sectime).toString())) ;
										}else if(tp.getPlugin().equals("mintime") && String.valueOf(value.get(tp.getFieldname().toLowerCase())).matches("[\\d]{1,}")) {
											int mintime = (int)Long.parseLong(String.valueOf(value.get(tp.getFieldname().toLowerCase())))/1000 ;
											cell2.setCellValue(new XSSFRichTextString(new UCKeFuTime(0,0,(int)mintime).toString())) ;
										}
									}else {
										cell2.setCellValue(new XSSFRichTextString(String.valueOf(value.get(tp.getFieldname().toLowerCase()))));
									}
								}
								//特别标注创建人姓名
								if("creater".equals(tp.getFieldname().toLowerCase())){
									UserRepository userRepository = UKDataContext.getContext().getBean(UserRepository.class);
									User user = userRepository.findByIdAndOrgi(value.get(tp.getFieldname().toLowerCase()).toString(), value.get("orgi").toString());
									if(user != null){
										cell2.setCellValue(new XSSFRichTextString(user.getUname()));
									}
								}
							}
						}
					}
				}
				
				for(TableProperties tp : table.getTableproperty()){
					if(tp.isUnresize() == true) {
						String json = (String) value.get(tp.getFieldname()) ;
						if(!StringUtils.isBlank(json)) {
							List<SysDic> dicList = UKeFuDic.getInstance().getDic("com.dic.xiaoe.input") ;
							@SuppressWarnings("unchecked")
							Map<String, String> values = UKTools.toObject(json,HashMap.class) ;
							for(SysDic sysDic : dicList) {
								Cell cell2 = row2.createCell(cols++); 
								cell2.setCellStyle(cellStyle); 
								List<SysDic> subDicList = UKeFuDic.getInstance().getDic("com.dic.xiaoe.input", sysDic.getId()) ;
								if(subDicList!=null && subDicList.size() > 0) {
									for(SysDic subDic : subDicList) {
										if(values.get(sysDic.getCode()).equals(subDic.getCode()) || values.get(sysDic.getCode()).equals(subDic.getId())) {
											cell2.setCellValue(new XSSFRichTextString(subDic.getName()));
										}
									}
								}else {
									cell2.setCellValue(new XSSFRichTextString(values.get(sysDic.getCode())));
								}
							}
						}
					}
				}
				if(tempExportDatas.size() > 0) {
					for(ExportData expData : tempExportDatas) {
						for(int i=0 ; i<expData.getMaxcols() && (cols + i)<256 ; i++) {
							if(titleRow.getCell(cols + i) == null) {
								Cell title = titleRow.createCell(cols + i); 
								title.setCellStyle(firstStyle); 
								title.setCellValue(new XSSFRichTextString(expData.getTp().getName()));
							}
						}
						
						for(String itemValue : expData.getValues()) {
							if(cols < 255) {
								Cell cell2 = row2.createCell(cols++);
								cell2.setCellValue(new XSSFRichTextString(itemValue));
							}
						}
					}
				}
				rowNum ++ ;
			}
		}
	}
	
	
	private CellStyle baseCellStyle(){
		CellStyle cellStyle = wb.createCellStyle();
		cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); 

		cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); 
				
		cellStyle.setWrapText(true);
		cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
		cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
		
		Font font = wb.createFont(); 
		font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); 
		//font.setFontName("宋体"); 
		font.setFontHeight((short) 200); 
		cellStyle.setFont(font); 
		
		return cellStyle;
	}
}
